package com.kll.tv.views

import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Toast
import androidx.core.widget.NestedScrollView
import com.bumptech.glide.Glide
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.GetSystemMenuDetailResponse
import com.kll.carolinehmibiz.net.bean.RefreshTokenResponse
import com.kll.carolinehmibiz.presentation.listener.InternalLinksDetailsProtocol
import com.kll.carolinehmibiz.presentation.listener.MainContactServiceProtocol
import com.kll.carolinehmibiz.presentation.presenter.InternalLinksDetailsPresenter
import com.kll.carolinehmibiz.presentation.presenter.MainContactServicePresenter
import com.kll.tv.R
import com.kll.tv.base.views.BaseActivity
import com.kll.tv.databinding.ActivityInternalLinksDetailsBinding
import com.kll.tv.utils.AppToast
import com.kll.carolinehmibiz.base.utils.L
import com.kll.tv.utils.PopWindow
import com.kll.tv.utils.TUICallingService
import com.kll.tv.utils.piputils.PIPManager
import com.kll.tv.utils.piputils.Tag
import com.kll.tv.views.adapter.ConnectServicePopAdapter
import com.tencent.liteav.trtccalling.model.TUICalling
import com.tencent.liteav.trtccalling.model.impl.TUICallingManager
import com.tencent.liteav.trtccalling.model.util.TUICallingConstants
import com.tencent.qcloud.tuicore.util.ToastUtil
import com.yanzhenjie.permission.AndPermission
import xyz.doikki.videocontroller.StandardVideoController
import xyz.doikki.videoplayer.ijk.IjkPlayer
import xyz.doikki.videoplayer.player.VideoView
import xyz.doikki.videoplayer.player.VideoViewManager


/**
 * 内部链接详情页
 */
class InternalLinksDetailsActivity : BaseActivity<InternalLinksDetailsPresenter>(),
    InternalLinksDetailsProtocol.IView,
    MainContactServiceProtocol.IView {
    private lateinit var binding: ActivityInternalLinksDetailsBinding
    private var menuId = 0
    private var popConnectServiceWindow: PopWindow? = null
    private var connectServicePopAdapter: ConnectServicePopAdapter? = null
    var mCallName: String? = null
    var mCallType: TUICalling.Type? = null
    private var mainContactServicePresenter: MainContactServicePresenter? = null
    private var rightPhotoData: ArrayList<String>? = null // 右边图片列表数据
    private var rightVideoData: ArrayList<String>? = null // 右边视频列表数据
    private var mVideoView: VideoView<IjkPlayer>? = null
    private var mController: StandardVideoController? = null
    private var mPIPManager: PIPManager? = null

    override fun initViewBinding(): View {
        binding = ActivityInternalLinksDetailsBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): InternalLinksDetailsPresenter {
        return InternalLinksDetailsPresenter(this, this)
    }

    override fun init() {
        menuId = intent.getIntExtra("menuId", 0)
        binding.tvTitle.text = intent.getStringExtra("menuTitle")

        mainContactServicePresenter = MainContactServicePresenter(this, this)

        initVideoView()
        initData()
        initListener()
    }

    private fun initData() {
        if (menuId != 0) {
            // 加载数据
            mPresenter.getArticle(menuId)
        }
        TUICallingService.getInstance(this).login()
    }

    var frameLayout: FrameLayout? = null

    private fun initListener() {
        binding.ivBack.setOnClickListener { finish() }
        binding.ivBackCircular.setOnClickListener {
            startActivity(Intent(this, MainActivity::class.java))
            finish()
        }
        // 咨询预约
        binding.tvContactService.setOnClickListener {
            // 弹窗
            toShowConnectServicePop()
        }
        // 客服聊天
        binding.ivServiceChat.setOnClickListener {
            // 弹窗
            toShowConnectServicePop()
        }
        // 滚动监听
        binding.scrollView.setOnScrollChangeListener(object :
            NestedScrollView.OnScrollChangeListener {
            override fun onScrollChange(
                v: NestedScrollView?,
                scrollX: Int,
                scrollY: Int,
                oldScrollX: Int,
                oldScrollY: Int
            ) {
                if(frameLayout != null && mVideoView?.parent != null) {

                    var location = IntArray(2)
                    frameLayout!!.getLocationInWindow(location)

                    var videoViewY = location[1] - binding.scrollView.y

                    if(videoViewY < -frameLayout!!.height || videoViewY > binding.scrollView.height) {
                        if(!mPIPManager!!.isStartFloatWindow ) {
                            if(Settings.canDrawOverlays(applicationContext)){
                                mPIPManager?.startFloatWindow()
                            }else{
                                L.e("---------","nonojnohnnononononon")
                            }

                           /* AndPermission
                                .with(this@InternalLinksDetailsActivity)
                                .overlay()
                                .onGranted(Action { data: Void? ->  })
                                .onDenied(Action { data: Void? -> })
                                .start()*/

                        }
                    } else if(mPIPManager!!.isStartFloatWindow){
                        mPIPManager?.stopFloatWindow()
                        if(mVideoView!!.parent == null) {
                            frameLayout?.addView(mVideoView)
                        }
                    }

                }
            }

        })
    }

    override fun getRoomIdSuccess(tecentUserId: String,roomid: String) {
        if (TUICallingService.getInstance(this).isLogin()) {
            val userIDs = arrayOf(tecentUserId)
            val bundle = Bundle()
            bundle.putString(TUICallingConstants.PARAM_NAME_TYPE, mCallName)
            bundle.putStringArray(TUICallingConstants.PARAM_NAME_USERIDS, userIDs)
            bundle.putString(TUICallingConstants.PARAM_NAME_GROUPID, "")
            TUICallingManager.sharedInstance().call(userIDs,roomid, mCallType)
        } else {
            ToastUtil.toastLongMessage("分配客服失败，请重试！")
        }
    }

    override fun getRoomIdFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.getArticle(menuId)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    // 弹窗
    private var toShowConnectServicePopIsBusying = false
    private fun toShowConnectServicePop() {
        if (toShowConnectServicePopIsBusying) return
        toShowConnectServicePopIsBusying = true
        if (popConnectServiceWindow == null) {
            popConnectServiceWindow = PopWindow(this)
            connectServicePopAdapter = ConnectServicePopAdapter(this, View.OnClickListener { v ->
                when (v.id) {
                    // 语音通话
                    R.id.iv_voice -> {
                        mCallName = TUICallingConstants.TYPE_AUDIO
                        mCallType = TUICalling.Type.AUDIO
                        mainContactServicePresenter!!.getAssignCustomerService()
                    }
                    // 视频通话
                    R.id.iv_video -> {
                        mCallName = TUICallingConstants.TYPE_VIDEO
                        mCallType = TUICalling.Type.VIDEO
                        mainContactServicePresenter!!.getAssignCustomerService()
                    }
                    // 取消
                    R.id.tv_cancel -> {
                        popConnectServiceWindow!!.dismiss()
                    }
                }
            })
            popConnectServiceWindow!!.addView(connectServicePopAdapter)
            popConnectServiceWindow!!.animationStyle = R.style.popwindow_anim_style
        }
        popConnectServiceWindow!!.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
        toShowConnectServicePopIsBusying = false
    }

    private fun startFloatWindow() {
        AndPermission
            .with(this)
            .overlay()
            .onGranted { data: Void? -> mPIPManager!!.startFloatWindow() }
            .onDenied { data: Void? -> }
            .start()
    }

    /**
     * 获取二级菜单详情成功
     */
    override fun getArticleSuccessed(data: ArrayList<GetSystemMenuDetailResponse>) {
        if (data.isNotEmpty()) {
            rightPhotoData = getSpecialResult(false, data[0].content_2!!)
            rightVideoData = getSpecialResult(true, data[0].content_2!!)

            // 这个页面只能是模版3
            if (data[0].template == 3) {
                // 循环左边的图片
                for (index in data[0].content_1!!) {
                    val imageView1 = ImageView(this)
                    val layoutParams = LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                    )
                    imageView1.layoutParams = layoutParams
                    Glide.with(this).load(index.url).into(imageView1)
                    binding.llContent1.addView(imageView1)
                }
                // 循环右边的图片
                for ((index, item) in rightPhotoData!!.withIndex()) {
                    val imageView = ImageView(this)
                    val layoutParams = LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                    )
                    layoutParams.height = 304
                    layoutParams.bottomMargin = 10
                    imageView.layoutParams = layoutParams
                    Glide.with(this).load(item).into(imageView)
                    imageView.setOnClickListener {
                        // 点击了图片
                        val intent = Intent(this, ImageReviewActivity::class.java)
                        val bundle = Bundle()
                        val photos = rightPhotoData
                        bundle.putSerializable("data", photos)
                        intent.putExtra("data", bundle)
                        intent.putExtra("index", index)
                        startActivity(intent)
                    }
                    binding.llContent2.addView(imageView)
                }
                // for循环右边的视频
                for ((index, item) in rightVideoData!!.withIndex()) {
                    val frameLayout = FrameLayout(this)
                    val frameLayoutParams = FrameLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                    )
                    frameLayoutParams.height = 304
                    frameLayoutParams.bottomMargin = 10
                    frameLayout.layoutParams = frameLayoutParams
                    frameLayout.setBackgroundResource(R.drawable.img_video_bg)

                    frameLayout.setOnClickListener {
                        if (mVideoView!!.parent != null) {
                            if (mVideoView!!.parent is FrameLayout) {
                                (mVideoView!!.parent as FrameLayout).removeView(mVideoView)
                            }
                            startPay(item)

                        } else {
                            mVideoView!!.setUrl(item)
                            mVideoView!!.start()
                        }
                        (it as FrameLayout).addView(mVideoView)
                        this.frameLayout = (it as FrameLayout)


                    }

                    binding.llContent2.addView(frameLayout)
                }
            }
        } else {
            startActivity(
                Intent(
                    this,
                    ExternalLinksDetailsActivity::class.java
                ).putExtra("menuTitle", intent.getStringExtra("menuTitle"))
                    .putExtra("url", intent.getStringExtra("menuTitle"))
            )
            finish()
        }
    }

    private fun initVideoView() {
        mPIPManager = PIPManager.getInstance()
        mVideoView = VideoViewManager.instance().get(Tag.PIP) as VideoView<IjkPlayer>?
        mController = StandardVideoController(this)
        mController!!.addDefaultControlComponent("标题", false)
        mVideoView!!.setVideoController(mController)
    }

    /**
     * 播放视频
     */
    private fun startPay(url: String) {
        L.v(">>>>>", "pay url = $url")

        mVideoView!!.setUrl(url)
        mVideoView!!.start()
        mVideoView!!.replay(true)
    }


    /**
     * 获取二级菜单详情失败
     */
    override fun getArticleFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.getArticle(menuId)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * 分配客服成功
     */
    override fun assignCSSuccessed(accountNo: String) {
        mainContactServicePresenter!!.getRoomId(accountNo)
    }

    /**
     * 分配客服加载中
     */
    override fun showAssignCSLoading() {
        Toast.makeText(this, "获取中...", Toast.LENGTH_SHORT).show()
    }

    /**
     * 分配客服失败
     */
    override fun assignCSFailed(code: Int, message: String) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show()
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mainContactServicePresenter!!.getAssignCustomerService()
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }


    override fun onPause() {
        super.onPause()
        mPIPManager?.pause()
    }

    override fun onResume() {
        super.onResume()
        mPIPManager?.resume()
    }

//    override fun onBackPressed() {
//        if (mPIPManager?.onBackPress()!!) return
//    }

    override fun onDestroy() {
        super.onDestroy()
        // 销毁presenter
        mainContactServicePresenter!!.onDismiss()
        mPIPManager?.reset()
    }

    /**
     * @param isType false 过滤出图片 true过滤出视频
     * 过滤arraylist
     */
    private fun getSpecialResult(
        isType: Boolean,
        arrays: ArrayList<GetSystemMenuDetailResponse.ImageInfo>
    ): ArrayList<String> {
        val resultArrays = ArrayList<String>()
        for (special in arrays) {
            if (!isType) {
                if (special.type == 1) {
                    resultArrays.add(special.url)
                }
            } else {
                if (special.type == 2) {
                    resultArrays.add(special.url)
                }
            }
        }
        return resultArrays
    }

    override fun setRequestedOrientation(requestedOrientation: Int) {
        return;
    }

}